<?php

namespace App\Http\Controllers\Steward;

use App\Models\Bill\BillPrintLog;
use App\Models\Bill\BillReturn;
use App\Models\Bill\BillGoodsSale;
use App\Models\Bill\BillTrace;
use App\Models\ConfigureFunction;
use App\Models\Mall\MallMaster;
use App\Models\Sys\SysDistribution;
use App\Models\Takeout\TakeoutBill;
use App\Models\Bill\BillGoods;
use App\Models\Mall\MallUser;


use App\Models\Takeout\TakeoutGoodsstockLess;
use Faker\Provider\Uuid;
use Illuminate\Http\Request;
use Carbon\Carbon;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

use App\Service\WdhService;

use Illuminate\Support\Facades\Redis as Redis;


use App\Models\Bill\Bill;
use Mockery\CountValidator\Exception;


class OrderController extends Controller
{

    /**
     * 订单外卖信息
     * @var array
     */
    private static $takeout_platform = [
        '30' => 'baidu',
        '31' => 'meituan',
        '32' => 'eleme',
        '33' => 'jd'
    ];

    /**
     * 外卖平台取消订单原因
     * @var array
     */
    private static $cancel_reason_item = [
        '30' => [
            ['item_id' => 1, 'item_name' => '不在配送范围内'],
            ['item_id' => 2, 'item_name' => '餐厅已打烊',],
            ['item_id' => 3, 'item_name' => '美食已售完'],
            ['item_id' => 4, 'item_name' => '菜品价格发生变化'],
            ['item_id' => 5, 'item_name' => '用户取消订单'],
            ['item_id' => 6, 'item_name' => '重复订单'],
            ['item_id' => 7, 'item_name' => '餐厅太忙'],
            ['item_id' => 8, 'item_name' => '联系不上用户'],
            ['item_id' => 9, 'item_name' => '假订单'],
            ['item_id' => -1, 'item_name' => '']
        ],
        '31' => [
            ['item_id' => 2007, 'item_name' => ''],
            ['item_id' => 2008, 'item_name' => '店铺太忙'],
            ['item_id' => 2009, 'item_name' => '商品已售完'],
            ['item_id' => 2010, 'item_name' => '地址无法配送'],
            ['item_id' => 2011, 'item_name' => '店铺已打烊'],
            ['item_id' => 2012, 'item_name' => '联系不上用户'],
            ['item_id' => 2013, 'item_name' => '重复订单'],
            ['item_id' => 2014, 'item_name' => '配送员取餐慢'],
            ['item_id' => 2015, 'item_name' => '配送员送餐慢'],
            ['item_id' => 2016, 'item_name' => '配送员送餐慢']
        ],
        '32' => [
            ['item_id' => 'fakeOrder', 'item_name' => '用户信息不符'],
            ['item_id' => 'foodSoldOut', 'item_name' => '商品已经售完'],
            ['item_id' => 'restaurantClosed', 'item_name' => '商家已经打烊'],
            ['item_id' => 'distanceTooFar', 'item_name' => '超出配送范围'],
            ['item_id' => 'restaurantTooBusy', 'item_name' => '商家现在太忙'],
            ['item_id' => 'forceRejectOrder', 'item_name' => '用户申请取消'],
            ['item_id' => 'deliveryFault', 'item_name' => '配送出现问题'],
            ['item_id' => 'notSatisfiedDeliveryR', 'item_name' => '不满足起送要求'],
        ],
        '33' => []
    ];

    //订单列表
    public function index($id)
    {
        $data = [
            'id'=>$id
        ];
        return view('steward/order/index',$data);
    }


    public function search(Request $request,$id)
    {
        $mallID = Redis::get('WDH_STEWARD_MALL_ID_' . session_id()) ? Redis::get('WDH_STEWARD_MALL_ID_' . session_id()) : 0;
        $type  = $request->input('type');
        $page  = $request->input('page',1);
        $limit  = $request->input('limit',10);
        $search = $request->input('search');
        //返回数据内容
        $return_data = [
            'link' => '',
            'total' => 0,
            'type'      => $type,
            'rows' => array(),
        ];

        $express_array = [
            ['id'=>0, 'name'=>'自配送']
        ];
        $res_distribution = SysDistribution::where('useFlg',1)->get()->toArray();
        if ($res_distribution) {
            foreach($res_distribution as $item) {
                $express_array[] = ['id' => $item['id'], 'name' => $item['name']];
            }
        }

        if($id == 1){
            $bill_data = [];
            if($type == 1){   //待接单

                $bill_data = Bill::where(['hang_up'=>0,'bill_status'=>1,'order_receive'=>0,'mallID'=>$mallID])
                    ->where('split_type','<>',2)
                    ->where(function ($query){
                        $query->where('pay_type',1)
                            ->orWhere(function ($query){
                                $query->where('pay_type',2)
                                    ->where('pay_status',1);
                            });
                    })
                    ->orderBy('bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 2){        //待发货

                $bill_data = Bill::where(['hang_up'=>0,'order_receive'=>1,'mallID'=>$mallID])
                    ->whereNotIn('bill_status',[0,2,4,5])
                    ->where('split_type','<>',2)
                    ->where(function ($query){
                        $query->where('pay_type',1)
                            ->orWhere(function ($query){
                                $query->where('pay_type',2)
                                    ->where('pay_status',1);
                            });
                    })
                    ->orderBy('bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 3){        //配送中

                $bill_data = Bill::where(['hang_up'=>0,'bill_logistics_status'=>2,'order_receive'=>1,'mallID'=>$mallID,'bill_status'=>2])
                    ->where('split_type','<>',2)
                    ->where(function ($query){
                        $query->where('pay_type',1)
                            ->orWhere(function ($query){
                                $query->where('pay_type',2)
                                    ->where('pay_status',1);
                            });
                    })
                    ->orderBy('bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 4){   //异常单

                $bill_data = Bill::where(['hang_up'=>1,'mallID'=>$mallID])
                    ->where('split_type','<>',2)
                    ->where(function ($query){
                        $query->where('pay_type',1)
                            ->orWhere(function ($query){
                                $query->where('pay_type',2)
                                    ->where('pay_status',1);
                            });
                    })
                    ->orderBy('bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 5){         //催单


                $bill_data = Bill::join('takeout_bill', 'bill_master.bill_no','=','takeout_bill.bill_no')
                    ->where(['hang_up'=>0,'mallID'=>$mallID,'takeout_bill.remind'=>1])
                    ->where('split_type','<>',2)
                    ->where(function ($query){
                        $query->where('pay_type',1)
                            ->orWhere(function ($query){
                                $query->where('pay_type',2)
                                    ->where('pay_status',1);
                            });
                    })
                    ->orderBy('bill_master.bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 6){     //退单

                $bill_data = Bill::join('takeout_bill', 'bill_master.bill_no','=','takeout_bill.bill_no')
                    ->where(['bill_master.hang_up'=>0,'bill_master.mallID'=>$mallID,'bill_master.billType'=>21])
                    ->where('takeout_bill.apply_cancel','>',0)
                    ->where('bill_master.split_type','<>',2)
                    ->where(function ($query){
                        $query->where('pay_type',1)
                            ->orWhere(function ($query){
                                $query->where('pay_type',2)
                                    ->where('pay_status',1);
                            });
                    })
                    ->orderBy('bill_master.bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 7){    //已完成

                $bill_data = Bill::where(['hang_up'=>0,'mallID'=>$mallID,'bill_status'=>4])
                    ->where('split_type','<>',2)
                    ->orderBy('bill_no','desc')
                    ->paginate($limit)
                    ->toArray();

            }elseif($type == 8){      //已取消
                $bill_data = Bill::where(['hang_up'=>0,'mallID'=>$mallID,'bill_status'=>5])
                    ->where('split_type','<>',2)
                    ->orderBy('bill_no','desc')
                    ->paginate($limit)
                    ->toArray();
            }

        }else{

            $where_search['mallID'] = $mallID;

            if(isset($search['custID']) && !empty($search['custID']) ){
                $where_search['custID'] = $search['custID'];
            }


            if(isset($search['bill_no']) && !empty($search['bill_no']) ){
                $where_search['bill_no'] = $search['bill_no'];
            }

            if(isset($search['deliver_name']) && !empty($search['deliver_name']) ){
                $where_search['deliver_name'] = $search['deliver_name'];
            }

            if(isset($search['mobile']) && !empty($search['mobile']) ){
                $where_search['deliver_mobile'] = $search['mobile'];
            }

            $bill_data = Bill::where($where_search)
                ->orderBy('bill_no','desc')
                ->paginate($limit)
                ->toArray();
        }



        //分页
        $page_link = "";
        if ($bill_data['total']) {
            $page_link = page($page, $bill_data['total'], $limit, 'javascript:void(0)', 'steward.page');
        }

        $return_data['link'] = (string)$page_link;
        $return_data['total'] = $bill_data['total'];

        if($bill_data['data']){
            foreach($bill_data['data'] as $key => $bill) {

                $bill['apply_cancel'] = 0;
                $bill['remind'] = 0;
                $bill['datetime'] = '';
                $bill['return_no'] = '';

                if ( isset($bill['mallID']) && $bill['mallID'] >0  ) {
                    $res_mall = MallMaster::select('mallCode', 'mallName', 'address')->where('mallID',$bill['mallID'])->get()->toArray();
                    if ($res_mall) {
                        $bill['mallCode'] = $res_mall[0]['mallCode'];
                        $bill['mallName'] = $res_mall[0]['mallName'];
                        $bill['address'] = $res_mall[0]['address'];
                    }
                }

                if (!empty($bill['send_time'])) {
                    $bill['datetime'] = str_replace(',','~',$bill['send_time']);
                } else {
                    if(!empty($bill['pickup_start_time']) && !empty($bill['pickup_end_time'])){
                        $m_d_start = date('m-d', strtotime($bill['pickup_start_time']));
                        $m_d_end = date('m-d', strtotime($bill['pickup_end_time']));
                        $m_time_start = date('H:i', strtotime($bill['pickup_start_time']));
                        $m_time_end = date('H:i', strtotime($bill['pickup_end_time']));
                        $bill['datetime'] = $m_d_start . ' ' . $m_time_start . ' ~';
                        if ($m_d_start != $m_d_end) {
                            $bill['datetime'] .= $m_d_end;
                        }
                        $bill['datetime'] .= ' ' . $m_time_end;
                    }
                }

                if (isset($bill['ziti']) && $bill['ziti'] == 1) {
                    $bill['address_name'] = empty($bill['zt_id']) ? $bill['mallName'] : $bill['zt_name'];

                    if(!empty($bill['pickup_start_time']) && !empty($bill['pickup_end_time'])){
                        if(date('m-d',strtotime($bill['pickup_start_time'])) == date('m-d',strtotime($bill['pickup_end_time']))){
                            $bill['datetime'] = '--';
                        }else{
                            $m_d_start = date('m-d', strtotime($bill['pickup_start_time']));
                            $m_d_end = date('m-d', strtotime($bill['pickup_end_time']));
                            $m_time_start = date('H:i', strtotime($bill['pickup_start_time']));
                            $m_time_end = date('H:i', strtotime($bill['pickup_end_time']));
                            $bill['datetime'] = $m_d_start . ' ' . $m_time_start . ' ~';
                            if ($m_d_start != $m_d_end) {
                                $bill['datetime'] .= $m_d_end;
                            }
                            $bill['datetime'] .= ' ' . $m_time_end;
                        }
                    }else{
                        $bill['datetime'] = '--';
                    }

                } else {
                    $bill['address_name'] = $bill['deliver_address'];

                    if (!empty($bill['send_time'])) {
                        $bill['datetime'] = str_replace(',','~',$bill['send_time']);
                    } else {
                        $bill['datetime'] = '--';
                    }
                }

                if ($bill['billType'] == 21) {

                    $res_takeout = TakeoutBill::select('out_bill_no','platform', 'apply_cancel','remind','remind_number','remind_time','apply_cancel_reason')
                        ->where('bill_no',$bill['bill_no'])->get()->toArray();

                    if ( isset($res_takeout) && !empty($res_takeout) ) {
                        $bill['apply_cancel'] = $res_takeout[0]['apply_cancel'];
                        $bill['remind'] = $res_takeout[0]['remind'];
                        $bill['remind_number'] = $res_takeout[0]['remind_number'];
                        $bill['remind_time'] = $res_takeout[0]['remind_time'];
                        $bill['billPlatform'] = $res_takeout[0]['platform'];
                        $bill['apply_cancel_reason'] = $res_takeout[0]['apply_cancel_reason'];
                    }
                    if ($bill['remind'] == 1) {
                        $bill['remind_reply'] =  [
                            '已送出', '正在烹饪', '天气原因', '人手不齐', '其它原因'
                        ];
                    }


                    //异常单原因
                    $takeout_goodsstock_less = TakeoutGoodsstockLess::where('bill_no',$bill['bill_no'])->where('mold',1)->get()->toArray();
                    if($takeout_goodsstock_less){
                        $bill['abnormal_cause'] = '库存不足';
                    }else{
                        $bill['abnormal_cause'] = '';
                    }
                }

                if ($bill['bill_return_status'] > 0) {
                    $return_data =BillReturn::where('bill_no',$bill['bill_no'])->where(['return_status'=>2,'service_type'=>1])->get()->toArray();
                    if (isset($return_data['return_no'])) {
                        $bill['return_no'] = $return_data['return_no'];
                    }
                }

                //当前用户下单次数
                $count_bill = Bill::where('pcustID',$bill['pcustID'])->where('createTime','<=',$bill['createTime'])->count();
                if ($count_bill) {
                    $bill['ordernum'] = $count_bill;
                }

                //外卖平台logo
                $platform_logo = '';
                if (isset(self::$takeout_platform[$bill['billPlatform']])) {
                    if( $bill['billPlatform'] == 30){
                        $platform_logo ='/static/images/steward/order/order-icon5.png';
                    }elseif( $bill['billPlatform'] == 31){
                        $platform_logo ='/static/images/steward/order/order-icon4.png';
                    }elseif( $bill['billPlatform'] == 32){
                        $platform_logo ='/static/images/steward/order/order-icon1.png';
                    }elseif( $bill['billPlatform'] == 33){
                        $platform_logo ='/static/images/steward/order/order-icon3.png';
                    }
                }

                //自提和配送标示
                $ziti_logo = "";
                if(in_array($bill['ziti'],[0,1])){
                    if ($bill['ziti'] == 1) {
                        $ziti_logo ='/static/images/steward/order/order-icon2.png';
                    }else{
                        $ziti_logo ='/static/images/steward/order/order-icon6.png';
                    }
                }

                //订单取消原因
                $reasons = [];
                if (!isset(self::$cancel_reason_item[$bill['billPlatform']])) {

                    $return_data[] = [
                        'reasonId' => '0',
                        'reasonContent' => ''
                    ];
                    $configure = ConfigureFunction::select('configure_json')->where('function_id',37)->get()->toArray();
                    if (isset($configure[0]['configure_json'])) {
                        $cancel_json = json_decode($configure[0]['configure_json'], true);
                        if (isset($cancel_json['configure'])) {
                            $cancel_reasons = $cancel_json['configure'];
                        }
                    }

                } else {
                    $cancel_reasons = self::$cancel_reason_item[$bill['billPlatform']];
                }

                if (isset($cancel_reasons)) {
                    foreach($cancel_reasons as $item) {
                        $reasons[] = [
                            'reasonId' => $item['item_id'],
                            'reasonContent' => $item['item_name']
                        ];
                    }
                }
                $bill_status_name = '';
                switch ($bill['bill_status']){
                    case 1:

                        if($bill['order_receive'] == 0){
                            $bill_status_name = '待接单';
                        }else{
                            $bill_status_name = '待发货';
                        }
                        break;
                    case 2:
                        $bill_status_name = '已发货';
                        break;
                    case 4:
                        $bill_status_name = '已完成';
                        break;
                    case 5:
                        $bill_status_name = '已取消';
                        break;
                    case 7:
                        $bill_status_name = '配货中';
                        break;
                    case 8:
                        $bill_status_name = '配货完成';
                        break;
                    case 10:
                        $bill_status_name = '异常单';
                        break;
                    case 12:
                        $bill_status_name = '退单';
                        break;
                }

                //判断是否开启配货流程
                $configure_function = ConfigureFunction::select('configure_json')->where(['function_id'=>21])->get()->toArray();
                $open_allot = 0;
                if($configure_function){
                    $configure_json = json_decode($configure_function[0]['configure_json'],true);
                    $open_allot  = $configure_json['configure']['open_allot'];
                }

                //操作按钮的判断
                $html = '';
                $html .= '<div class="submit-btn">';
                if($bill['hang_up'] == 1 ){
                    $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','cancel_hang','$type'".')" type="button">取消异常</button>';
                }else{

                    //回复催单
                    if($bill['remind'] == 1){

                        $html .='<select class="form-control reminder" style="display: inline-block;width:120px;">';
                        $html .='<option value="">选择内容</option>';
                        for( $i = 0 ; $i < count($bill['remind_reply']); $i++){
                            $html .='<option value='.($i+1).'>'.$bill['remind_reply'][$i].'</option>';
                        }
                        $html .='</select>';
                        $html .='<button class="btn btn-primary" onclick="bill.remind_reply('."'".$bill['bill_no']."','$type',this".')"  type="button">回复用户</button>';
                    }

                    //待接单
                    if($bill['order_receive'] == 0){

                        if($bill['bill_status'] == 1){

                            $html .='<select class="form-control cancel_reasons" name="search_state" style="width: 150px;display: inline-block;">';
                            $html .='<option value="">选择取消内容</option>';
                            if (isset($reasons) && !empty($reasons)){
                                foreach ($reasons as $list){
                                    $html .='<option value='.$list['reasonId'].'>'.$list['reasonContent'].'</option>';
                                }
                            }
                            $html .='</select>';
                            $html.= '<button class="btn btn-primary" onclick="bill.cancel('."'".$bill['bill_no']."','$type',this".')"  type="button">取消</button>';
                            $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','receive','$type'".')"  type="button">接单</button>';

                        }
                    }else{

                        //代发货
                        if(!in_array($bill['bill_status'],[0,2,4,5])){

                            if($open_allot == 1 ){             //开启配货

                                if($bill['bill_status'] == 8){

                                    $html .='<select class="form-control select" name="search_state" style="width: 135px;display: inline-block;">';
                                    $html .='<option value="">选择配送平台</option>';
                                    foreach ($express_array as $list){
                                        $html .='<option value='.$list['id'].'>'.$list['name'].'</option>';
                                    }
                                    $html .='</select>';
                                    $html.= '<button class="btn btn-primary" onclick="bill.delivery('."'".$bill['bill_no']."','$type',this".')" type="button">发货</button>';

                                }else{

                                    $html .='<select class="form-control cancel_reasons" name="search_state" style="width: 150px;display:inline-block;">';
                                    $html .='<option value="">选择取消内容</option>';
                                    if (isset($reasons) && !empty($reasons)){
                                        foreach ($reasons as $list){
                                            $html .='<option value='.$list['reasonId'].'>'.$list['reasonContent'].'</option>';
                                        }
                                    }
                                    $html .='</select>';
                                    $html.= '<button class="btn btn-primary"  onclick="bill.cancel('."'".$bill['bill_no']."','$type',this".')"  type="button">取消</button>';

                                    if($bill['bill_status'] == 1 ){
                                        $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','packs','$type'".')"  type="button">配货</button>';
                                    }else if($bill['bill_status'] == 7 ){
                                        $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','packsFinish','$type'".')" type="button">配货完成</button>';
                                    }
                                }

                            }
                        }

                        //配送中
                        if($bill['bill_status'] == 2 ){
                            $html.= '<button class="btn btn-primary"  onclick="bill.operation('."'".$bill['bill_no']."','finish','$type'".')" type="button">完成</button>';
                        }
                    }



                    //退款订单和取消订单
                    if($bill['apply_cancel'] > 0){

                        $html.= '<input type="text" class="form-control refund" placeholder="请输入拒绝原因" style="width: 125px;display: inline-block">';
                        $html.= '<button class="btn btn-primary" onclick="bill.disagreRefund('."'".$bill['bill_no']."','$type',this".')" type="button">拒绝</button>';

                        if($bill['apply_cancel'] == 1 ){
                            $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','agreRefund','$type'".')"  type="button">同意取消</button>';
                        }elseif ( $bill['apply_cancel']  == 2 ){
                            $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','agreRefund','$type'".')"  type="button">同意退款</button>';
                        }
                    }

                    $http_user_agent = $request->server('HTTP_USER_AGENT');

                    if( in_array($bill['bill_status'],[1,2,4,5,7,8]) && strpos($http_user_agent, '.NET')){
                        $html.= '<button class="btn btn-primary" type="button" onclick="client_print('."'".$bill['bill_no']."'".');">打印</button>';
                    }

                    if(in_array($bill['bill_status'],[1,2,7,8]) || $bill['remind'] == 1){
                        $html.= '<button class="btn btn-primary" onclick="bill.operation('."'".$bill['bill_no']."','hang','$type'".')"  type="button">挂起</button>';
                    }
                }
                $html.= '</div>';

                $return_data['rows'][] = [
                    'bill_no'        =>strval($bill['bill_no']),
                    'create_at'      =>date('m-d H:i',strtotime($bill['createTime'])),
                    'ziti_logo'      =>$ziti_logo,
                    'deliver_name'   => !empty($bill['deliver_name'])?$bill['deliver_name']:"",
                    'deliver_mobile' =>$bill['deliver_mobile'],
                    'adress'          =>$bill['address_name'],
                    'date_time'       =>$bill['datetime'],
                    'bill_totalPaid' =>$bill['bill_totalPaid'],
                    'bill_status'     => $bill['bill_status'],
                    'bill_status_name'=> $bill_status_name,
                    'takeout_knight_delivery' => 0, //外卖骑士配送，此种情况，配货流程和发货流程及妥投操作禁用
                    'apply_cancel'    => $bill['apply_cancel'], //外卖取消申请
                    'remind'           => $bill['remind'],//催单提醒
                    'remind_reply'    => isset($bill['remind_reply']) ? $bill['remind_reply'] : [],//催单回复
                    'remind_number'   => isset($bill['remind_number']) ? $bill['remind_number'] : 0,//催单次数
                    'remind_time'     => isset($bill['remind_time']) ?$bill['remind_time'] : '',//催单时间
                    'platLogo'         => $platform_logo,
                    'ordernum'         => isset($bill['ordernum']) ? $bill['ordernum'] : 0,//当前用户下单数量
                    'endtime'          =>'', //接单剩余时间
                    'remark'           =>!empty($bill['remark'])?$bill['remark']:"",               //订单备注
                    'add_html'       => $html,
                    'bill_total_amount' => $bill['bill_total_amount']
                ];
            }
        }

        return response()->json($return_data);
    }

    /**
     * 订单详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */

    public function detail($bill_no,$bill_status)
    {
        if ( empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数bill_no']);
        }

        //查询订单信息
        $bill_data = Bill::find($bill_no);

        if (empty($bill_data)) {
            return response()->json(['code'=>100003, 'message'=>'订单信息没有找到']);
        }

        //返回值
        $return_data=array(
            'bill_no'=>$bill_no,//订单号
            'ziti'=>$bill_data['ziti'],//是否自提 1、是 0否
            'pay_type'=>$bill_data['pay_type'],//主支付方式类型：1、货到付款 2、在线支付 3、汇款
            'payTypeID'=>$bill_data['payTypeID'],//主支付方式ID
            'payTypeName'=>$bill_data['payTypeName'],//主支付方式名称
            'sendTypeID'=>$bill_data['sendTypeID'],//配送方式ID
            'sendTypeName'=>$bill_data['sendTypeName'],//配送方式名称
            'bill_totalPaid'=>$bill_data['bill_totalPaid'],//商品总金额
            'deliver_fee'=>$bill_data['deliver_fee'],//运费
            'bill_coupon_money'=>$bill_data['bill_coupon_money'],//订单优惠券订单金额
            'bill_points_money'=>$bill_data['bill_points_money'],//订单积分抵扣金额
            'bill_balance_money'=>$bill_data['bill_balance_money'],//订单余额抵扣金额
            'bill_subtract_money'=>$bill_data['bill_subtract_money'],//订单立减金额
            'bill_payable'=>$bill_data['bill_payable'],//应付总金额
            'remark'=>$bill_data['remark'],//备注留言
            'billPlatform'=>$bill_data['billPlatform'],//订单平台：1、自营、2、天猫、3、京东、4、1号店、5、QQ网购、6、凡客、7、苏宁易购 8、易讯 9、拍拍 10、亚马逊 11、当当 12、淘宝 13、实体店 30、百度外卖 31、美团外卖 32、饿了么外卖 33、京东到家
            'mallName'=>$bill_data['mallName'],//门店名称
            'createTime'=>$bill_data['createTime'],//创建时间
            'barcode'=>$bill_data['barcode'],//订单提货券码
            'order_receive'=>$bill_data['order_receive'],//已接单:0、否 1、是
            'deliver_name'=>$bill_data['deliver_name'],//收货人姓名
            'hang_up'=>$bill_data['hang_up'],//是否挂起
            'bill_cut_money'=>($bill_data['bill_coupon_money']+$bill_data['bill_points_money']+$bill_data['bill_balance_money']),//优惠金额（所有可算优惠金额）
            'bill_status_name'=>$bill_status,
            'bill_status'=>$bill_data['bill_status'],
            'bill_logistics_status'=>$bill_data['bill_logistics_status']
        );


        //订单取消原因
        $reasons = [];
        if (!isset(self::$cancel_reason_item[$bill_data['billPlatform']])) {

            $return_data[] = [
                'reasonId' => '0',
                'reasonContent' => ''
            ];
            $configure = ConfigureFunction::select('configure_json')->where('function_id',37)->get()->toArray();
            if (isset($configure[0]['configure_json'])) {
                $cancel_json = json_decode($configure[0]['configure_json'], true);
                if (isset($cancel_json['configure'])) {
                    $cancel_reasons = $cancel_json['configure'];
                }
            }

        } else {
            $cancel_reasons = self::$cancel_reason_item[$bill_data['billPlatform']];
        }

        if (isset($cancel_reasons)) {
            foreach($cancel_reasons as $item) {
                $reasons[] = [
                    'reasonId' => $item['item_id'],
                    'reasonContent' => $item['item_name']
                ];
            }
        }

        $return_data['reasons']=$reasons;

        //查询配送信息
        $trace_data=BillTrace::where('bill_no',$bill_no)->get()->toArray();
        $trace_arr=array();
        foreach($trace_data as $key=>$trace){
            $trace_arr[$key]['createTime']=$trace['createTime'];//创建时间
            $trace_arr[$key]['content']=$trace['content'];//内容
            $trace_arr[$key]['creator']=$trace['creator'];//创建人
        }

        $return_data['trace_arr']=$trace_arr;
        $trace_num=count($return_data['trace_arr']);
        $return_data['trace_num']=$trace_num;

        //查询商品信息
        $goods_data=BillGoods::getGoods($bill_no);
        $goods_num=count($goods_data);
        $return_data['goods_num']=$goods_num;
        $goods_list=array();

        foreach($goods_data as $key=>$goods)
        {
            $goods_sale_data=BillGoodsSale::getGoods( $goods['goods_postID'] );
            $goods_list[$key]['mainPostID']=$goods_sale_data['mainPostID'];//主网购号
            $goods_list[$key]['img_url']=$goods_sale_data['goodsMainPic'];//图片地址
            $goods_list[$key]['product_code']=$goods['product_code'];//SKU商家编码
            $goods_list[$key]['goods_name']=$goods['goods_name'];//商品名
            $goods_list[$key]['goods_spec']=$goods['goods_spec'];//规格
            $goods_list[$key]['productId']=$goods['goods_postID'];//网购号
            $goods_list[$key]['price']=$goods['goods_storePrice'];//销售价格
            $goods_list[$key]['goods_purchasePrice']=$goods['goods_purchasePrice'];//实售价格
            $goods_list[$key]['goods_amount']=$goods['goods_amount'];//销售数量
            $goods_list[$key]['goodsprice']=$goods['goods_purchasePrice']*$goods['goods_amount'];//总金额
        }

        $return_data['goods_list']=$goods_list;

        //查询退货信息
        $bill_return_data=BillReturn::find($bill_no);
        if($bill_return_data)
        {
            $return_data['return_no']=$bill_return_data['return_no'];
        }

        //查询外卖信息
        $takeout_data=TakeoutBill::find($bill_no);
        if($takeout_data)
        {
            $return_data['cover_bill_no']=$takeout_data['out_bill_no'];//外卖平台订单号
            $return_data['apply_cancel']=$takeout_data['apply_cancel'];//申请取消单/退单:0、无申请 1、申请取消单 2、申请退单
            $return_data['apply_cancel_reason']=$takeout_data['apply_cancel_reason'];//申请取消的理由
            $return_data['remind']=$takeout_data['remind'];//是否催单
        }
        //查询门店信息
        $mallID=$bill_data['mallID'];
        $mall_data=MallMaster::find($mallID);
        $return_data['mall_phone']=$mall_data['phone'];//电话
        $return_data['mall_address']=$mall_data['address'];//地址

        //下单总量
        $count_bill = Bill::where('pcustID',$bill_data['pcustID'])->where('createTime','<=',$bill_data['createTime'])->count();
        if ($count_bill) {
            $return_data['ordernum']=$count_bill;
        }

        //是否支付
        $pay_status = '未支付';
        if($bill_data['pay_type'] == 2 && $bill_data['pay_status'] == 1){
            $pay_status = '已支付';
        }
        $return_data['is_pay']=$pay_status;

        //发票信息
        $invoice_arr=array(
            'invoice'=>$bill_data['invoice'],//索取发票 1、是 0、否
            'invoiceID'=>$bill_data['invoiceID'],//发票id
            'invoice_type'=>$bill_data['invoice_type'],//发票类型： 1、商业零售发票
            'invoice_title_type'=>$bill_data['invoice_title_type'],//发票抬头类型 1：个人 2：单位
            'invoice_title'=>$bill_data['invoice_title'],//发票抬头
            'invoice_content_id'=>$bill_data['invoice_content_id'],//发票内容ID
            'invoice_content'=>$bill_data['invoice_content'],//发票内容
            'invoice_amount'=>$bill_data['invoice_amount']//发票金额
        );
        $return_data['invoice_arr']=$invoice_arr;

        //地址信息
        $delivery_arr=array(
            'deliverid'=>$bill_data['deliverid'],//收货地址id
            'deliver_name'=>$bill_data['deliver_name'],//收货人姓名
            'deliver_province'=>$bill_data['deliver_province'],//收货地址省
            'deliver_provinceid'=>$bill_data['deliver_provinceid'],//收货地址省ID
            'deliver_city'=>$bill_data['deliver_city'],//收货地址市
            'deliver_cityid'=>$bill_data['deliver_cityid'],//收货地址市ID
            'deliver_county'=>$bill_data['deliver_county'],//收货地址区
            'deliver_countyid'=>$bill_data['deliver_countyid'],//收货地址区ID
            'deliver_address'=>$bill_data['deliver_address'],//收货地址
            'deliver_mobile'=>$bill_data['deliver_mobile']//收货人手机
        );
        $return_data['delivery_arr']=$delivery_arr;

        //结算金额信息
        $cost_arr=array(
            'additional_expenses'=>$bill_data['additional_expenses'],//订单附加费用
            'deliver_fee'=>$bill_data['deliver_fee'],//应收运费
            'bill_coupon_money'=>$bill_data['bill_coupon_money'],//订单优惠券订单金额
            'bill_subtract_money'=>$bill_data['bill_subtract_money'],//订单立减金额
            'bill_payable'=>$bill_data['bill_payable']//应付款金额
        );
        $return_data['cost_arr']=$cost_arr;


        //外卖平台logo
        $platform_logo = '';
        if (isset(self::$takeout_platform[$bill_data['billPlatform']])) {
            if( $bill_data['billPlatform'] == 30){
                $platform_logo ='/static/images/steward/order/order-icon5.png';
            }elseif( $bill_data['billPlatform'] == 31){
                $platform_logo ='/static/images/steward/order/order-icon4.png';
            }elseif( $bill_data['billPlatform'] == 32){
                $platform_logo ='/static/images/steward/order/order-icon1.png';
            }elseif( $bill_data['billPlatform'] == 33){
                $platform_logo ='/static/images/steward/order/order-icon3.png';
            }
        }
        $return_data['billPlatform_logo']=$platform_logo;

        //自提和配送标示
        $ziti_logo = "";
        if(in_array($bill_data['ziti'],[0,1])){
            if ($bill_data['ziti'] == 1) {
                $ziti_logo ='/static/images/steward/order/order-icon2.png';
            }else{
                $ziti_logo ='/static/images/steward/order/order-icon6.png';
            }
        }
        $return_data['ziti_logo']=$ziti_logo;

        //自提
        if ( $bill_data['ziti'] == 1 ) {
            $return_data['ziti_arr'] = [
                'mallID'   => $bill_data['mallID'],
                'mallCode' => $bill_data['mallCode'],
                'mallName' => $bill_data['mallName'],
            ];

            if(date('m-d',strtotime($bill_data['pickup_start_time'])) == date('m-d',strtotime($bill_data['pickup_end_time']))){
                $return_data['pickup_time'] = '--';
            }else{
                $return_data['pickup_time'] = date('m-d H:i',strtotime($bill_data['pickup_start_time'])). '~' .date('m-d H:i',strtotime($bill_data['pickup_end_time']));
            }

        } else {

            if (!empty($bill_data['send_time'])) {
                $send_time = $bill_data['send_time'];
            } else {
                $send_time = '--';
            }

            $return_data['deliver_time'] = $send_time;
        }

        //判断是否开启配货流程
        $configure_function = ConfigureFunction::select('configure_json')->where(['function_id'=>21])->get()->toArray();
        $open_allot=0;
        if($configure_function){
            $configure_json = json_decode($configure_function[0]['configure_json'],true);
            $open_allot  = $configure_json['configure']['open_allot'];
        }

        $return_data['open_allot']=$open_allot;

        $express_array = [
            ['id'=>0, 'name'=>'自配送']
        ];
        $res_distribution = SysDistribution::where('useFlg',1)->get()->toArray();
        if ($res_distribution) {
            foreach($res_distribution as $item) {
                $express_array[] = ['id' => $item['id'], 'name' => $item['name']];
            }
        }
        $return_data['express_array']=$express_array;

        $bill=array();
        if ($bill_data['billType'] == 21) {

            $res_takeout = TakeoutBill::select('out_bill_no', 'platform', 'apply_cancel', 'remind', 'remind_number', 'remind_time', 'apply_cancel_reason')
                ->where('bill_no', $bill_no)->get()->toArray();

            if (isset($res_takeout) && !empty($res_takeout)) {
                $bill['apply_cancel'] = $res_takeout[0]['apply_cancel'];
                $bill['remind'] = $res_takeout[0]['remind'];
                $bill['remind_number'] = $res_takeout[0]['remind_number'];
                $bill['remind_time'] = $res_takeout[0]['remind_time'];
                $bill['billPlatform'] = $res_takeout[0]['platform'];
                $bill['apply_cancel_reason'] = $res_takeout[0]['apply_cancel_reason'];
            }
            if ($bill['remind'] == 1) {
                $bill['remind_reply'] = [
                    '已送出', '正在烹饪', '天气原因', '人手不齐', '其它原因'
                ];
            }
        }
        if($bill!=array())
        {
            $return_data['remind']=$bill['remind'];//催单提醒
        }else{
            $return_data['remind']='';//催单提醒
        }
        $return_data['remind_reply']=isset($bill['remind_reply']) ? $bill['remind_reply'] : [];//催单回复
        $return_data['remind_number']= isset($bill['remind_number']) ? $bill['remind_number'] : 0;//催单次数
        $return_data['remind_time']=isset($bill['remind_time']) ?$bill['remind_time'] : '';//催单时间

        $button=array();
        if($return_data['hang_up']==1)//异常
        {
            $button[]=1;//取消异常按钮
        }else{//非异常

            if( in_array($bill_data['bill_status'],[1,2,4,5,7,8]) ){
               $button[]=2;//打印按钮
            }

            if(in_array($bill_data['bill_status'],[1,2,7,8]) || $return_data['remind'] == 1){
               $button[]=3;//挂起按钮
            }

            //退款订单和取消订单
            if(isset($return_data['apply_cancel']))
            {
                if($return_data['apply_cancel']>0)
                {
                    $button[]=4;//拒绝（按钮） 原因
                    if($return_data['apply_cancel']==1)
                    {
                        $button[]=5;//同意取消按钮
                    }else if($return_data['apply_cancel']==2)
                    {
                        $button[]=6;//同意拒绝按钮
                    }
                }
            }

            //回复催单
            if(!empty($return_data['remind']))
            {
                if($return_data['remind']==1)
                {
                    $button[]=7;//回复用户，选择内容按钮
                }
            }

            //待接单
            if($return_data['order_receive']==0)
            {
                if($return_data['bill_status']==1)
                {
                    $button[]=8;//选择取消内容，取消按钮，接单按钮
                }
            }else{//配送中

                if($return_data['bill_status']==2)
                {
                    $button[]=9;//完成按钮
                }
                //待发货
                if(!in_array($return_data['bill_status'],[0,2,4,5]))
                {
                    //开启配货
                    if($open_allot == 1)
                    {
                        if($return_data['bill_status']==8)
                        {
                            $button[]=10;//选择配送平台，发货按钮
                        }else{
                            $button[]=11;//选择取消内容，取消按钮
                            if($return_data['bill_status'] == 1)
                            {
                                $button[]=12;//配货按钮
                            }
                            if($return_data['bill_status'] == 7)
                            {
                                $button[]=13;//配货完成按钮
                            }
                        }
                    }
                }
            }

        }
        $return_data['button']=$button;
       //var_dump($return_data);die;
        return view('steward/order/detail', $return_data);
    }


    /**
     * 同意申请取消单/退单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */

    public function agreRefund (Request $request) {

        $bill_no = $request->input('bill_no');

        if ( !isset( $bill_no ) || empty($bill_no)) {
            return response()->json([ 'code' => 400 , 'message' => '缺少参数bill_no']);
        }

        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $userName = MallUser::where('user_id',$user_id)->get()->toArray();

        $apply_cancel = 0;
        $opreator = '营业员' . $userName[0]['mobile'];

        $bill_data = Bill::where('bill_no',$bill_no)->get()->toArray();

        if (!$bill_data) {
            return response()->json([ 'code' => 404 , 'message' => '订单信息没有找到']);
        } else if ($bill_data[0]['bill_status'] == 5) {
            return response()->json([ 'code' => 404 , 'message' => '订单已取消']);
        }else if($bill_data[0]['bill_status'] == 4){
            return response()->json([ 'code' => 404 , 'message' => '订单已经完成']);
        }else if($bill_data[0]['bill_status'] == 1){
            return response()->json([ 'code' => 404 , 'message' => '订单未发货']);
        }else if($bill_data[0]['bill_status'] == 0){
            return response()->json([ 'code' => 404 , 'message' => '订单未审核']);
        }

        $bill_obj = $bill_data[0];

        if ($bill_obj['billType'] == 21) {
            $takeout_bill = TakeoutBill::where('bill_no',$bill_no)->get()->toArray();
            if(!$takeout_bill){
                return response()->json([ 'code' => 404 , 'message' => '该订单号不存在']);
            }
            $apply_cancel = $takeout_bill[0]['apply_cancel'];
        }

        $reason = $apply_cancel == 2 ? '用户退单' : '用户取消单';

        try {

            DB::beginTransaction();

            if ($apply_cancel == 2) {

                $back_data = [
                    'bill_no' =>$bill_no,
                    'opreator' =>$opreator,
                    'reason' =>$reason,
                    'type' =>false
                ];

                $res = WdhService::backOrder($back_data);
            } else {

                $takeout_data = [
                    'bill_no' =>$bill_no,
                    'custID' =>$opreator,
                    'cancel_reason' =>$reason,
                    'bill_status' =>5,
                    'is_enter_erp' =>true,
                    'isTracsaction' =>false,
                    'is_deliver_cancel' =>1,
                ];

                $res = WdhService::cancel($takeout_data);
            }

            if ( $res['code'] != 200) {
                return response()->json([ 'code' => 400 , 'message' => '操作失败,请刷新页面！']);
            }

            if (isset($takeout_bill)) {
                TakeoutBill::where('bill_no',$bill_no)->update(['apply_cancel'=>0]);
                $res = WdhService::bill_takeout([
                    'bill_no' => $bill_no,
                    'alias' =>self::$takeout_platform[$bill_obj['billPlatform']],
                    'type' => 'agreeRefund'
                ]);
                if ($res['code'] != 200) {
                    return response()->json([ 'code' => 400 , 'message' => '订单接口调取失败，请重试']);
                }
            }

            DB::commit();
            return response()->json([ 'code' => 200 , 'message' => 'ok']);

        } catch (Exception $e) {
           DB::rollBack();

            if ($e->getCode() > 0) {
                return response()->json([ 'code' => $e->getCode() , 'message' => $e->getMessage()]);
            } else {
                return response()->json([ 'code' => 500 , 'message' => '系统错误']);
            }
        }
    }


    /**
     * 不同意申请
     * @package  $request
     * @return array
     * **/
    public function disagreRefund (Request $request) {

        $bill_no      = $request->input('bill_no');
        $cancel_reason = $request->input('cancel_reason');

        if ( !isset( $bill_no ) || empty($bill_no)) {
            return response()->json([ 'code' => 400 , 'message' => '缺少参数bill_no']);
        }

        if ( !isset( $cancel_reason ) || empty($cancel_reason)) {
            return response()->json([ 'code' => 400 , 'message' => '缺少参数cancel_reason']);
        }

        $bill_data = Bill::where('bill_no',$bill_no)->get()->toArray();

        if ( !$bill_data ) {
            return response()->json([ 'code' => 404 , 'message' => '订单信息没有找到']);
        }

        $bill_obj = $bill_data[0];
        if ($bill_obj['billType'] == 21) {

            $takeout_data = TakeoutBill::where('bill_no',$bill_no)->get()->toArray();

            if(!$takeout_data){
                return response()->json([ 'code' => 404 , 'message' => '该订单号不存在']);
            }
            $res = WdhService::bill_takeout([
                'bill_no' => $bill_no,
                'alias' =>self::$takeout_platform[$bill_obj['billPlatform']],
                'type' => 'disagreeRefund',
                'content' => $cancel_reason
            ]);
            if ($res['code'] != 200) {
                return response()->json([ 'code' => 400 , 'message' => '接口调用失败，请重试！']);
            }

            $update = [
                'apply_cancel'  =>0,
                'apply_cancel_reason' => $cancel_reason
            ];

            TakeoutBill::where('bill_no',$bill_no)->update($update);
        }

        return response()->json([ 'code' => 200 , 'message' => 'ok']);

    }

    /**
     * 订单发货接口
     * @param $request
     * @return array
     */
    public function delivery(Request $request)
    {

        $bill_no     = $request->input('bill_no' );
        $express_id  = $request->input('express_id' );

        if ( !isset( $bill_no ) || empty($bill_no)) {
            return response()->json([ 'code' => 400 , 'message' => '缺少参数bill_no' ]);
        }

        //获取操作者信息
        $user_id    = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $userName   = MallUser::where('user_id',$user_id)->get()->toArray();
        $bill_no    = $request->input('bill_no');
        $express_id = isset($express_id) ? $express_id : '';
        $opreator   = '营业员'. $userName[0]['mobile'];

        $bill_data = Bill::where('bill_no',$bill_no)->get()->toArray();

        if(!$bill_data){
            return response()->json([ 'code' => 400 , 'message' => '订单信息不存在' ]);
        }elseif($bill_data[0]['order_receive'] != 1){
            return response()->json([ 'code' => 400 , 'message' => '订单未接单' ]);
        }

        $bill_master = $bill_data[0];

        $error_array = [
            2 => '订单已发货',
            4 => '订单已完成',
            5 => '订单已取消',
        ];

        if ( isset( $error_array[$bill_master['bill_status']] ) ) {
            return response()->json([ 'code' => 400 , 'message' => $error_array[$bill_master['bill_status']]] );
        }else if ( $bill_master['bill_refund_status'] > 0 ) {
            return response()->json([ 'code' => 400 , 'message' => '订单已申请退款']);
        }

        $update = [
            'bill_logistics_status' =>0,
            'bill_status'            =>2,
            'verify_time'            =>date('Y-m-d H:i:s')
        ];

        if($bill_master['ziti'] != 1){

            if (!in_array($express_id, ['0', 1, 2])) {
                return response()->json([ 'code' => 400 , 'message' => '订单配送方式错误']);
            }

            if ($express_id == 0) {

                $update['bill_logistics_status']  = 0;
                $update['bill_status']             = 2;
                $update['verify_time']             = date('Y-m-d H:i:s');
                $update['send_deliver_type']      =1;
                $update['bill_logistics_status'] =2;
                $update['express_company']        ='门店自配送';
                $update['express_number']         ='';

            } else {

                if ($express_id == 1) {
                    $express_company = '达达';
                    $send_url = G_WEBSITE_DOMAINNAME.'/logistics/data/order';
                } else {
                    $express_company = '蜂鸟';
                    $send_url = G_WEBSITE_DOMAINNAME .'/logistics/fengniao/order';
                }

                $update['send_deliver_type']      = 2;
                $update['bill_status']             = 2;
                $update['verify_time']             = date('Y-m-d H:i:s');
                $update['bill_logistics_status']  = 1;
                $update['express_company']         = $express_company;


                $goods_arr = [];
                $goods_list = BillGoods::getGoods($bill_no);
                if($goods_list){
                    foreach($goods_list as $val){
                        $goods_arr[] = [
                            'product_code' => $val['product_code'],
                            'goods_name' => $val['goods_name'],
                            'goods_amount' => $val['goods_amount'],
                            'goods_storePrice' => $val['goods_storePrice'],
                            'goods_purchasePrice' => $val['goods_purchasePrice'],
                        ];
                    }

                    $mall_master = MallMaster::where(['mallID'=>$bill_master['mallID']])->toArray();
                    $send_request = [
                        'goods' => $goods_arr,
                        'is_invoiced' => $bill_master['invoice'],
                        'remark'       => $bill_master['remark'],
                        'bill_no'      => $bill_master['bill_no'],
                        'mallCode'     => $bill_master['mallCode'],
                        'mallName'     => $bill_master['mallName'],
                        'mallAddress'  => $bill_master['address'],
                        'mallLng'       => $mall_master['longitude'],
                        'mallLat'       => $mall_master['latitude'],
                        'mallPhone'     => $mall_master['phone'],
                        'bill_totalMoney' => $bill_master['bill_totalMoney'],
                        'bill_payable'  => $bill_master['bill_payable'],
                        'pay_status'    => $bill_master['pay_status'],
                        'pay_type'       => $bill_master['pay_type'],
                        'bill_total_amount'=> $bill_master['bill_total_amount'],
                        'deliver_name'    => $bill_master['deliver_name'],
                        'deliver_mobile'  => $bill_master['deliver_mobile'],
                        'deliver_cityid'  => $bill_master['deliver_cityid'],
                        'deliver_address' => $bill_master['deliver_address'],
                    ];
                }
            }
        }

        try {

            DB::beginTransaction();

            Bill::where('bill_no',$bill_no)->update($update);       //更新订单主表

            BillTrace::insert([                    //更新订单轨迹表
                'creator'=>$opreator,
                'bill_no'=>$bill_no,
                'bill_status'=>2,
                'content'=>'您的订单已发货'.$opreator,
                'uuid'=>makeUuid(),
                'createTime'=>date('Y-m-d H:i:s'),
            ]);

            WdhService::pushBillToErp([
             'bill_status' => 2,
             'bill_no' => $bill_no
            ]);

            if (isset($send_request, $send_url)) {

                ebsig_require('module/base/common/ebsigHttp.class.php');
                $ebsigHttp = new ebsigHttp();
                $ebsigHttp->post( $send_url, $send_request );
            }

            if ($bill_master['billType'] == 21 && $bill_master['billPlatform'] == 31) {
                $res_takeout = WdhService::bill_takeout([
                    'bill_no' => $bill_master['bill_no'],
                    'alias' => self::$takeout_platform[$bill_master['bill_no']],
                    'type' => 'delivery'
                ]);
                if ($res_takeout['code'] != 200) {
                    return response()->json([ 'code' => 404 , 'message' => $res_takeout['message']]);
                }
            }
            DB::commit();
            return response()->json([ 'code' => 200 , 'message' => '订单操作成功']);

        }catch (Exception $e) {

            DB::rollBack();
            return response()->json([ 'code' => 400 , 'message' => '发货失败']);
        }
    }


    /**
     * 订单取消接口
     * @param $request
     * @return array
     */
    public function cancel(Request $request) {

        $bill_no  = $request->input('bill_no');
        $reason   = $request->input('reason');
        $reasonId = $request->input('reasonId');

        if ( !isset( $bill_no ) || empty($bill_no)) {
            return response()->json([ 'code' => 400 , 'message' => '缺少参数bill_no' ]);
        }

        if (!isset($reason) || empty($reason)){
            return response()->json([ 'code' => 400 , 'message' => '取消原因不能为空' ]);
        }

        if (!isset($reasonId) || empty($reasonId)){
            return response()->json([ 'code' => 400 , 'message' => '取消原因ID不能为空' ]);
        }

        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $userName = MallUser::where('user_id',$user_id)->get()->toArray();
        $opreator = '营业员：'.$userName[0]['mobile'];

        $error_array = [
            2 => '订单已发货，不能再取消',
            3 => '订单已配送，不能再取消',
            4 => '订单已完成，不能再取消',
            5 => '订单已取消，不能再取消'
        ];

        $res_bill = Bill::where('bill_no',$bill_no)->get()->toArray();

        if ( !$res_bill) {
            return response()->json([ 'code' => 404 , 'message' => '订单信息不存在']);
        }

        if (isset($error_array[$res_bill[0]['bill_status']])) {
            return response()->json([ 'code' => 404 , 'message' => $error_array[$res_bill[0]['bill_status']] ]);
        }

        try {

            DB::beginTransaction();

            $cancel = [
                'bill_no' =>$bill_no,
                'cancel_reason' =>$reason,
                'custID' =>$opreator,
                'bill_status' =>5
            ];
            $res = WdhService::cancel($cancel);
            if ( $res['code'] != 200) {
                return response()->json([ 'code' => $res['code'] , 'message' => $res['message'] ]);
            }

            if ($res_bill[0]['billType'] == 21) {
                $res_takeout = WdhService::bill_takeout([
                    'bill_no' => $res_bill[0]['bill_no'],
                    'alias' => self::$takeout_platform[$res_bill[0]['billPlatform']],
                    'content' => $reason,
                    'reasonId' => $reasonId,
                    'type' => 'cancel'
                ]);
                if ($res_takeout['code'] != 200) {
                    throw new Exception($res_takeout['message'],404);
                }
            }

            DB::commit();
            return response()->json([ 'code' => 200 , 'message' => '取消成功']);

        } catch (Exception $e) {
            DB::rollBack();

            return response()->json([ 'code' => 404 , 'message' => $e->getMessage()]);
        }
    }


    /**
     * 订单完成接口
     * @param $request
     * @return array
     */
    public function finish(Request $request) {


        $bill_no = $request->input('bill_no');
        if ( !isset( $bill_no ) || empty($bill_no)) {
            return response()->json([ 'code' => 400 , 'message' => '缺少参数bill_no' ]);
        }

        $bill_master = Bill::where('bill_no',$bill_no)->get()->toArray();

        if (!$bill_master) {
            return response()->json([ 'code' => 404 , 'message' => '订单信息没有找到']);
        }

        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $userName = MallUser::where('user_id',$user_id)->get()->toArray();
        $opreator = '营业员：'.$userName[0]['mobile'];

        try {

            DB::beginTransaction();

            $args_data = [
                'bill_no'=>$bill_no,
                'opreator' =>$opreator
            ];
            $res = WdhService::bill_finish($args_data);


            if ( $res['code'] != 200) {
                return response()->json([ 'code' => 400 , 'message' => '操作失败！']);
            }

            if ($bill_master['billType'] == 21) {
                $res = WdhService::bill_takeout([
                    'bill_no' => $bill_no,
                    'alias' =>self::$takeout_platform[$bill_master[0]['billPlatform']],
                    'type' => 'finish'
                ]);
                if ($res['code'] != 200) {
                    return response()->json([ 'code' => 404 , 'message' => '外卖平台接口失败']);
                }
            }

            DB::commit();
            return response()->json([ 'code' => 200 , 'message' => '操作成功！']);

        } catch (Exception $e) {

            DB::rollBack();
            return response()->json([ 'code' => 400 , 'message' => '订单完成失败' ]);
        }
    }


    /**
     * 确认退货接口
     * @package  $request
     * @return array
     *
     **/
    public function receiveReturn (Request $request) {

        $return_no = $request->input('return_no');
        if (!isset($return_no) || !ebsig_is_int($return_no)) {
            return response()->json([ 'code' => 400 , 'message' => '退货号信息不能为空' ]);
        }
        $opreator = $request->input('营业员：'.'employee_number','system');

        //退货的在线支付数组
        $online_pay_data = array();

        //退回的积分数组
        $points_data = array();

        //退货的余额数组
        $balance_data = array();

        //货到付款退款
        $refund_amount = 0;

        try {

            //查询退换货单信息
            $return_obj = BillReturn::where(['return_no'=>$return_no])->toArray();

            if (!$return_obj) {
                throw new Exception('退货单信息没有找到', 404);
            }
            if ($return_obj['return_status'] == 1) {
                throw new Exception('退货单未审核', 404);
            }
            if ($return_obj['return_status'] == 3) {
                throw new Exception('退货单已完成', 404);
            }
            if ($return_obj['return_status'] == 4) {
                throw new Exception('退货单未通过审核', 404);
            }
            if ($return_obj['return_status'] == 5) {
                throw new Exception('退货单已退款', 404);
            }

            //查询订单主表信息
            $bill_data = Bill::getBill($return_obj['bill_no'])->toArray();
            if (!$bill_data) {
                throw new Exception('订单信息没有找到', 404);
            }

            //查询订单支付信息
            $bill_pay_data = WdhService::bill_pay($return_obj['bill_no']);
            foreach($bill_pay_data as $pay) {
                if ($pay['type'] == 1) {
                    if ($bill_data['bill_status'] == 4) {
                        $refund_amount = $return_obj['return_price'];
                    }
                } else if ($pay['type'] == 2) {
                    $refund_amount = $return_obj['return_price'];
                    $online_pay_data = $pay;
                } else if ($pay['type'] == 4) {
                    $balance_data = array(
                        'amount' => $pay['pay_amount'],
                        'remark' => '订单' . $return_obj['bill_no'] . '退货，退回余额'
                    );
                } else if ($pay['type'] == 5) {
                    $points_data = array(
                        'points' => $pay['pay_amount'],
                        'remark' => '订单' . $return_obj['bill_no'] . '退货，退回积分'
                    );
                }
            }

        } catch (Exception $e) {

            return return_exception($e, '退货单收货');
        }


        try {

            DB::beginTransaction();

            //更新退货单
            BillReturn::where(['return_no'=>$return_no])->update(['return_status'=>3]);
            if (!empty($points_data) || !empty($online_pay_data) || !empty($balance_data) || $refund_amount > 0) {

                //生产已审核的退款单
                $refund_data = array(
                    'bill_no' => $bill_data['bill_no'],
                    'linkMan' => $bill_data['deliver_name'],
                    'mobile' => $bill_data['deliver_mobile'],
                    'refund_reason_id' => 0,
                    'refund_reason' => '订单退货',
                    'refund_amount' => $refund_amount,
                    'refund_source' => 1,
                    'refund_status' => empty($online_pay_data) ? 1 : 2,
                    'refund_type' => empty($online_pay_data) ? 1 : 2,
                    'operator' => $opreator,
                    'return_no' => $return_no,
                    'refund_onlinepay_status' => empty($online_pay_data) ? 0 : 2,
                    'confirmor' => 'system',
                    'confirm_time'  => date('Y-m-d H:i:s',time())
                );
                $result_data = WdhService::refund_single($refund_data);
                if ($result_data['code'] != 200) {
                    throw new Exception($result_data['message'], $result_data['code']);
                }

                //退款操作
                if (!empty($points_data) || !empty($online_pay_data) || !empty($balance_data)) {

                    //$result_data = $bill_refund_obj->refund($result_data['data']['refund_no'], $bill_data['pcustID'], $bill_data['custID'], $balance_data, $points_data, $online_pay_data);
                    if ($result_data['code'] != 200) {
                        throw new Exception($result_data['message'], $result_data['code']);
                    }
                }
            }

            DB::commit();

        } catch (Exception $e) {

            DB::rollBack();

            return return_exception($e, '新增退货');
        }

        return response()->json([ 'code' => 200 , 'message' => 'ok' ]);
    }

    /**
     * 订单接单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function receive(Request $request)
    {
        $bill_no = $request->input('bill_no');
        if (empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数bill_no']);
        }

        //获取操作者信息
        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $user    = MallUser::find($user_id);

        //查询订单信息
        $bill_data = Bill::find($bill_no)->toArray();

        if (empty($bill_data)) {
            return response()->json(['code'=>100003, 'message'=>'订单信息没有找到']);
        }

        if ($bill_data['order_receive'] == 1) {
            return response()->json(['code' => 100004, 'message' => '订单已接单']);
        }
        ;
        if ($bill_data['pay_type'] == 2 && $bill_data['pay_status'] != 1) {
            return response()->json(['code' => 100005, 'message' => '订单未付款']);
        }

        if ($bill_data['bill_refund_status'] > 0) {
            return response()->json(['code' => 100006, 'message' => '订单已申请退款']);
        }

        try {

            DB::beginTransaction();

            //修改订单主表信息
            Bill::where('bill_no', $bill_no)->update([
                'order_receive' => 1,
                'timeStamp' => Carbon::now()
            ]);

            if ($bill_data['billType'] == 21) {
                $res_takeout = WdhService::takeoutUpstream([
                    'bill_no' => $bill_no,
                    'alias'   => self::$takeout_platform[$bill_data['billPlatform']],
                    'type'    => 'receive'
                ]);

                if ($res_takeout['code'] != 200) {
                    return response()->json(['code' => 404, 'message' => $res_takeout['message']]);
                }
            }

            //新增订单轨迹
            BillTrace::insert(
                [
                    'creator'=>$user['name'],
                    'bill_no'=>$bill_no,
                    'bill_status'=>1,
                    'content'=>'您的订单已接单' . $user['name'],
                    'uuid'=>makeUuid(),
                    'createTime'=>date('Y-m-d H:i:s',time()),
                    'timeStamp'=>date('Y-m-d H:i:s',time())
                ]
            );
            DB::commit();
            return response()->json(['code' => 200, 'message' => '订单接单成功']);

        }catch (Exception $e) {

            DB::rollBack();

            return response()->json(['code' => 100007, 'message' => '订单接单失败']);
        }
    }

    /**
     * 回复催单
     * @param $request
     * @return array
     */
    public function remindReply (Request $request) {

        $reply_message = $request->input('reply_message');
        $bill_no       = $request->input('bill_no');

        if (!isset($bill_no) || empty($bill_no)) {
            return response()->json(['code' => 400, 'message' => '缺少参数bill_no']);
        }

        if (!isset($reply_message) || empty($reply_message)) {
            return response()->json(['code' => 400, 'message' => '缺少参数reply_message']);
        }

        //查询订单
        $bill_master = Bill::getBill($bill_no);
        if (!$bill_master) {
            return response()->json(['code' => 404, 'message' => '订单信息没有找到']);
        }

        if ($bill_master['billType'] == 21) {

            $takeout_bill = TakeoutBill::where(['bill_no'=>$bill_no]);
            if (!$takeout_bill) {
                return response()->json(['code' => 404, 'message' => '没有找到催单']);
            }

            $res = WdhService::takeoutUpstream([
                'bill_no' => $bill_no,
                'alias' =>self::$takeout_platform[$bill_master['billPlatform']],
                'type' => 'remindReply',
                'content' => $reply_message
            ]);

            if ($res['code'] != 200) {
                return response()->json(['code' => 404, 'message' => '订单接口调取失败，请重试']);
            }

            $update = [
                'remind' =>0,
                'remind_reply_message' =>$reply_message,
            ];
            TakeoutBill::where(['bill_no'=>$bill_no])->update($update);
        }

        return response()->json(['code' => 200, 'message' => '操作成功']);

    }


    /**
     * 订单挂起
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function hang(Request $request)
    {
        $bill_no=$request->input('bill_no');
        if ( empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '订单号信息不能为空']);
        }

        //查询订单信息
        $bill_data = Bill::find($bill_no);
        if (empty($bill_data)) {
            return response()->json(['code'=>100003, 'message'=>'订单信息没有找到']);
        }

        //修改订单主表信息
        Bill::where('bill_no', $bill_no)->update([
            'hang_up' => 1
        ]);

        return response()->json(['code' => 200, 'message' => '订单挂起成功']);
    }

    /**
     * 订单取消挂起
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelHang(Request $request)
    {
        $bill_no=$request->input('bill_no');
        if ( empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '订单号信息不能为空']);
        }

        //查询订单信息
        $bill_data = Bill::find($bill_no);
        if (empty($bill_data)) {
            return response()->json(['code'=>100003, 'message'=>'订单信息没有找到']);
        }

        //修改订单主表信息
        Bill::where('bill_no', $bill_no)->update([
            'hang_up' => 0
        ]);

        return response()->json(['code' => 200, 'message' => '订单取消挂起成功']);

    }

    /**
     * 订单配货
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function packs(Request $request)
    {

        $bill_no  = $request->input('bill_no');

        if (empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数bill_no']);
        }

        //获取操作者信息
        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $user = MallUser::find($user_id);

        //查询订单信息
        $bill_data = Bill::find($bill_no);


        if (empty($bill_data)) {
            return response()->json(['code'=>100003, 'message'=>'订单信息没有找到']);
        }


        if($bill_data['order_receive']!=1)
        {
            return response()->json(['code' => 100004, 'message' => '订单未接单']);
        }

        if($bill_data['bill_refund_status']>0)
        {
            return response()->json(['code' => 100005, 'message' => '订单已申请退款']);
        }


        try{
            DB::beginTransaction();

            //新增订单轨迹
            $trace = new BillTrace();
            $trace->creator = $user['name'];
            $trace->bill_no = $bill_no;
            $trace->bill_status = 7;
            $trace->timeStamp = Carbon::now() ;
            $trace->createTime = Carbon::now() ;
            $trace->uuid = makeUuid();
            $trace->content = '您的订单配货中,营业员:' . $user['name'];
            $trace->save();

            //修改订单主表信息
            Bill::where('bill_no',$bill_no)->update([
                'bill_status'=>7
            ]);

            DB::commit();

            return response()->json(['code' => 200, 'message' => '订单配货中']);

        }catch (Exception $re){

            DB::rollBack();

            return response()->json(['code' => 100007, 'message' => '订单配货失败']);
        }

    }


    /**
     * 配货完成
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function packsFinish(Request $request)
    {
        $bill_no  = $request->input('bill_no');

        if (empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数bill_no']);
        }

        //获取操作者信息
        $user_id = Redis::get('WDH_STEWARD_USER_ID_' . session_id());
        $user = MallUser::find($user_id);

        //查询订单信息
        $bill_data = Bill::find($bill_no);

        if (empty($bill_data)) {
            return response()->json(['code'=>100003, 'message'=>'订单信息没有找到']);
        }

        if($bill_data['bill_refund_status']>0)
        {
            return response()->json(['code' => 100005, 'message' => '订单已申请退款']);
        }

        try{

            DB::beginTransaction();

            //新增订单轨迹
            $trace = new BillTrace();
            $trace->creator = $user['name'];
            $trace->bill_no = $bill_no;
            $trace->bill_status = 8;
            $trace->timeStamp = Carbon::now() ;
            $trace->createTime = Carbon::now() ;
            $trace->uuid = makeUuid();
            $trace->content = '您的订单已打包完成,营业员' . $user['name'];
            $trace->save();

            //修改订单主表
            Bill::where('bill_no',$bill_no)->update([
                'bill_status'=>8
            ]);

            DB::commit();

            return response()->json(['code' => 200, 'message' => '订单配货完成']);

        }catch (Exception $re)
        {
            DB::rollBack();

            return response()->json(['code' => 100007, 'message' => '订单配货失败']);
        }

    }

    /**
     * 记录打印日志
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function printLog(Request $request){

        $bill_no = $request->input('bill_no');
        $device_site = $request->input('device_site');

        $bill_print_log = BillPrintLog::where('bill_no',$bill_no)->where('device_site',$device_site)->first();

        if(!$bill_print_log){

            $bill_print_log = new BillPrintLog();

            $bill_print_log->uuid = Uuid::uuid();
            $bill_print_log->creator = 'system';
            $bill_print_log->createTime = date('Y-m-d h:i:s');
            $bill_print_log->bill_no = $bill_no;
            $bill_print_log->device_site = $device_site;
            $bill_print_log->save();
        }

        return response()->json(['code'=>200,'message'=>'ok']);
    }

}